package Cliente.ventanas;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import Cliente.TCPCliente;

public class HistoricoWindow extends JFrame implements ActionListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private TCPCliente tcp;
	private JButton back;
	private JScrollPane scroll;
	
	public HistoricoWindow(SensorWindow sensor, TCPCliente tcp, int id){
		
		
		this.setLayout(null);
		this.setResizable(false);
		back = new JButton("Volver");
		back.addActionListener(this);
		
		this.tcp = tcp;
		HISTORICO(id).toArray();
		DefaultTableModel modelo = new DefaultTableModel();
		JTable tabla = new JTable(modelo);
		modelo.addColumn("Hora");
		modelo.addColumn("Posicion");
		modelo.addColumn("Valor");
		ArrayList<String> datos = HISTORICO(id);
		for(int i = 0;i<datos.size();i++){
			char ch = '0';
			int finPosicion = 0;
			String linea = datos.get(i);
			for(int j =20; ch!=';' && j<linea.length();j++){
				ch = linea.charAt(j);
				finPosicion = j;
			}
			String[] fila = {linea.substring(0,19),linea.substring(20,finPosicion),linea.substring(finPosicion+1,linea.length())};
			modelo.addRow(fila);
		}
		scroll = new JScrollPane(tabla);

		this.add(scroll);
		
		this.add(back);		
		
		scroll.setBounds(0, 0, 600, 350);
		back.setBounds(75,350,150,50);
		this.setSize(600,500);
		this.setVisible(true);
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.setAlwaysOnTop(true);
	}
	
	public ArrayList<String> HISTORICO (int id){
		ArrayList<String> array = new ArrayList<String>();
			boolean fin =false;
			try {
				tcp.sentMessage("HISTORICO "+id+"\n");
				while(!fin){
					String linea = tcp.receiveMessage();
					array.add(linea);
					if(linea.equals("222 OK ListaFinalizada."))
						fin = true;
				}
				array.remove(0);
				array.remove(0);
				array.remove(array.size()-1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return array;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		this.dispose();
	}

}
